/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2009 INRIA
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
 */

#ifndef BARRIER_H
#define BARRIER_H

#include <algorithm>
#include <pthread.h>
#include <stdint.h>

#include "spin-barrier-impl.h"

namespace ns3 {

/**
 *
 * \ingroup core
 *
 * \brief Base class for synchronization barriers implementations
 */
class Barrier
{
public:
  Barrier () {}
  virtual ~Barrier () {}
  virtual void Wait (void) = 0;
};

class PosixBarrier : public Barrier
{
public:
  PosixBarrier (uint32_t waiters) {
    pthread_barrier_init (&m_barrier, 0, waiters);
  }
  virtual ~PosixBarrier () {
    pthread_barrier_destroy (&m_barrier);
  }
  virtual void InitializeThread (void) {}
  virtual void Wait (void) {
    pthread_barrier_wait (&m_barrier);
  }
private:
  pthread_barrier_t m_barrier;
};

class GlobalSpinBarrier : public Barrier
{
public:
  GlobalSpinBarrier (uint32_t waiters)
    : m_barrier (waiters) {}
  virtual void Wait () {
    if (!m_initialized)
      {
        m_barrier.Initialize (&m_local);
        m_initialized = true;
      }
    m_barrier.Wait (&m_local);
  }
private:
  ns3::GlobalSpinBarrierImpl m_barrier;
  static __thread bool m_initialized;
  static __thread ns3::GlobalSpinBarrierContext m_local;
};

class TreeSpinBarrier : public Barrier
{
public:
  TreeSpinBarrier (uint32_t waiters)
    : m_barrier (waiters) {}
  virtual void Wait (void) {
    if (!m_initialized)
      {
        m_barrier.Initialize (&m_local);
        m_initialized = true;
      }
    m_barrier.Wait (&m_local);
  }
private:
  ns3::TreeSpinBarrierImpl m_barrier;
  static __thread bool m_initialized;
  static __thread ns3::TreeSpinBarrierContext m_local;
};

} // namespace ns3

#endif /* BARRIER_H */
